﻿


import Request from "../../base/request.js?t=202511041006"
import Storage from "../../base/storage.js?t=202511041006"
import { imageBaseUrl, downloadfun, isImageFile, IgetDeptList, IDeletePPEFile, queryURLParams, dealTime, getBrowserInfo } from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {
    const generateh = (text, isShort) => {
        if (isShort) {
            return h('div', {
                style: "width:100px;overflow:hidden;white-space: nowrap;text-overflow: ellipsis; -o-text-overflow: ellipsis;cursor:pointer"
            }, { default: () => text })
        } else {
            return h('div', {
                style: "width:300px;height:auto;"
            }, { default: () => text })
        }
    }
    const data = reactive({
        pdfOpen: false,
        pdfurl: "",


        messageTest: "",
        proxy: "",
        popShow: false,
        imgUrl: "",
        previewShow: false,
        uploadImg: {
            previewVisible: false,
            previewImage: "",
            previewTitle: "",
            fileList: [

            ]
        },
        isAll:false,
        itemRender: (data) => {

            let uid = data.file.uid
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnPreview(uid) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, { default: () => '预览' })
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDownLoad(uid) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, { default: () => '下载' })
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDelete(data) }, src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, { default: () => '删除' })
            var btns  = h('div', { style: "display:flex;margin-left:10px" }, {
                default: () => [
                    isImageFile(data.file.url)?previewBtn:null,
                    downloadBtn,
                    params.urlinfo.value.optype ? null : deleteBtn
                ]
            })


            return h('div', { style: 'margin-top:10px; width:400px;align-items:center; display:flex;justify-content:space-between' }, {
                default: () => [
                    data.file.name, btns
                ]
            })

        },
        editUploadList:[],
        uploadLock: false,
        deptList:[],
        formData: {
            Time: [],
            DepartmentIds: [],
            Title: null,
            NoticeContent: null,
            Remark:null,
        },
        urlinfo: {},
  
        
    })
    let params = toRefs(data)
    const methods = {
        setVisible: (value) => {
            params.previewShow.value = value;
        },

        btnPreview: (e) => {
            console.log(e,'ee')

            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            if (item.url.indexOf('.pdf') != -1) {
                params.pdfurl.value = item.url
                params.pdfOpen.value = true
            } else {
                params.imgUrl.value = item.url

                methods.setVisible(true)
            }
        },
        btnDownLoad: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            const { name, url } = item
            console.log(name, url)
            methods.downloadfun(name, url)

        },
        btnDelete: (e) => {
            const { FileId, uid } = e.file
            if (FileId) {
                IDeletePPEFile(Request, FileId).then(res => {
                    params.uploadImg.value.fileList = params.uploadImg.value.fileList.filter(es => es.uid != uid)
                    if (params.urlinfo.value.id) {

                        let index = params.editUploadList.value.findIndex(e => e == FileId)
                        if (index != -1) {
                            params.editUploadList.value.splice(index, 1)
                        }



                    }
                })
            }
        },
        handleChange: (info) => {

            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();
                formData.append('nfile', info.file.originFileObj)
                formData.append('uid', info.file.originFileObj.uid)
                Request({
                    url: "/download/uploadfile?Path=Performance/Plan",
                    method: 'post',
                    data: formData
                }).then(res => {

                    let item = params.uploadImg.value.fileList.find(e => e.uid == res.Data[0].uid)
                    item.url = imageBaseUrl + res.Data[0].FilePath.split('../..')[1]
                    item.FileId = res.Data[0].FileId
                    item.FileName = res.Data[0].FileName
                    item.name = res.Data[0].FileName
                    params.uploadLock.value = false
                    if (params.urlinfo.value.id) {
                        params.editUploadList.value.push(res.Data[0].FileId)
             

                    }

                })
            }



        },




        filterOption: (val, type) => {

            return `${type.label}`.includes(`${val || ''}`)
        },

        getBase64: (file) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
            })
        },




     

        handlePreview: async (file) => {

            if (!file.url && !file.preview) {
                file.preview = (await methods.getBase64(file.originFileObj));
            }
            params.uploadImg.value.previewImage = file.url || file.preview;
            params.uploadImg.value.previewVisible = true;
            params.uploadImg.value.previewTitle = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
        },

        onSubmit(Status) {

            if (params.urlinfo.value.id) {

  
                Request({
                    url: "/Performance/EditSimplePlan",
                    method: 'post',
                    data: {
                        Id: params.urlinfo.value.id,
                        ...params.formData.value,
                        StartTime: params.formData.value.Time && dayjs(params.formData.value.Time[0]).format('YYYY-MM-DD'),
                        EndTime: params.formData.value.Time && dayjs(params.formData.value.Time[1]).format('YYYY-MM-DD'),
                        FileList: params.editUploadList.value,
                        Status: Status,
                        DepartmentIds: params.formData.value.DepartmentIds.join(',')
                    }
                }).then(res => {

        
                    params.messageTest.value.info(res.Msg);
                    setTimeout(() => {
                        methods.onBack()
                    }, 1000)
              

                })
            } else {
    
                Request({
                    url: "/Performance/AddSimplePlan",
                    method: 'post',
                    data: {
                        ...params.formData.value,
                        StartTime: params.formData.value.Time && dayjs(params.formData.value.Time[0]).format('YYYY-MM-DD'),
                        EndTime: params.formData.value.Time && dayjs(params.formData.value.Time[1]).format('YYYY-MM-DD'),
                        FileList: params.uploadImg.value.fileList.map(e => e.FileId),
                        Status: Status,
                        DepartmentIds: params.formData.value.DepartmentIds.join(',')
                    }
                }).then(res => {

                    params.messageTest.value.info(res.Msg);
                    params.editUploadList.value=[]
                    setTimeout(() => {
                        methods.onBack()
                    }, 1000)


                })
            }

      

        },
        getDeptList: () => {
            return new Promise(async(resolve, rej) => {
                params.deptList.value = await IgetDeptList(Request)
                if (params.deptList.value ) {
                    resolve(1)
                }
            })

       
        },
        onBack: () => {
            window.location.href ='/Performance/PerformancePlanPageListNew'
        },

        
        GetSimplePlan: (id) => {
            Request({
                url: "/performance/GetSimplePlan",
                method: 'post',
                params: {
                    Id: id
                },
            }).then(res => {


                params.formData.value = res.Data
                params.formData.value.DepartmentIds = params.formData.value.DepartmentIds.split(',').map(e=>+e)
     
                params.formData.value.Time = [dayjs(dealTime(params.formData.value.StartTime)), dayjs(dealTime(params.formData.value.EndTime)) ]

                params.uploadImg.value.fileList = params.formData.value.FileList.map(e => {
                    return {
                        ...e,
                        url: e.FilePath,
                        name: e.FileName
                    }
                })

           
                    setTimeout(() => {
                        const { createEditor, createToolbar } = window.wangEditor;
               
                        const editorConfig = {
                            placeholder: "请输入通知内容",
                            onChange(editor) {
                                params.formData.value.NoticeContent = editor.getHtml();

                            },
                        };

                      var editor = createEditor({
                            selector: "#editor-container",
                            html: params.formData.value.NoticeContent,
                            config: editorConfig,
                            mode: "default", // or 'simple'
                      });
                        if (params.urlinfo.value.optype) {
                            editor.disable()
                        }
             
                        const toolbarConfig = {
                        };

                        toolbarConfig.excludeKeys = [
                            'group-image',
                            'group-video',
                            'codeBlock',
                            'emotion',
                            'todo',
                            'fullScreen' // 排除菜单组，写菜单组 key 的值即可
                        ]

                        const toolbar = createToolbar({
                            editor: editor,
                            selector: "#toolbar-container",
                            config: toolbarConfig,
                            mode: "default", // or 'simple'
                        });


                    }, 1000)


                

             
            })
        },
        allChoose: () => {
            params.isAll.value = !params.isAll.value
            if (params.isAll.value) {
                params.formData.value.DepartmentIds = params.deptList.value.map(e=>e.value)
            } else {
                params.formData.value.DepartmentIds=[]
            }

        },
   
        init: () => {
              getBrowserInfo().catch(err => { console.log(err)})
            params.urlinfo.value = queryURLParams()
     
            if (!params.urlinfo.value.id) {
         
                setTimeout(() => {
                    const { createEditor, createToolbar } = window.wangEditor;

                    const editorConfig = {
                        placeholder: "请输入通知内容",
                        onChange(editor) {
                            params.formData.value.NoticeContent = editor.getHtml();

              
                        },
                    };

                 var   editor = createEditor({
                        selector: "#editor-container",
                        html: "",
                        config: editorConfig,
                         mode: "simple", // or 'simple'
                    });

                    const toolbarConfig = {
                    };
                    toolbarConfig.excludeKeys = [
                        'group-image',
                        'group-video',
                        'codeBlock',
                        'emotion',
                        'todo',
                        'fullScreen' // 排除菜单组，写菜单组 key 的值即可
                    ]
                    const toolbar = createToolbar({
                        editor: editor,
                        selector: "#toolbar-container",
                        config: toolbarConfig,
                        mode: "default", // or 'simple'
                    });
   

                }, 1000)


            }

            let info = Storage.get('AccountInfo', true)
            Request({
                url: "/Account/createJwtToken",
                method: 'post',
                data: {
                    "userName": info && info.UserNo
                }
            }).then(res => {

                Storage.set('token', res.Data,true)

                methods.getDeptList().then(res => {

                    if (params.urlinfo.value.id) {
                        methods.GetSimplePlan(params.urlinfo.value.id)
                    }

                })




            })
    
  
            if (proxy) {
                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });
          
        },

    }
    const template = {
        pdfPopModel: {
            template: `
           <a-modal v-model:open="pdfOpen" width= "80%" title = "PDF预览" v-on:ok="pdfOpen=false" >
<div style='height:700px'>
                <embed id="pdfviewscreen" :src="pdfurl" type="application/pdf" width="100%" style="height:100%;" />

</div>
  
            </a-modal >
`,
            setup() {
                return {
                    ...params,
                    ...methods,
                };
            }
        },


        bottomBtns: {
            template: `<div class="w-full bg-[#eeeeee] h-50  flex  items-center justify-end pr-4">
                    <a-space>


  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(0)"
  >
 <a-button  :loading="uploadLock" v-if="!urlinfo.optype" type="dashed">保存</a-button>
  </a-popconfirm>

  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(1)"
  >
          <a-button  :loading="uploadLock" v-if="!urlinfo.optype" type="primary">提交</a-button>
  </a-popconfirm>
                       
              
                        <a-button v-on:click="onBack" :loading="uploadLock">返回</a-button>
                    </a-space>
                </div>`,
            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }
    return {
        ...params,
        ...methods,
        template
    }
}
export default Composition